//
//  ZQMeViewController.m
//  BuDeJie
//
//  Created by 仲琦 on 16/3/31.
//  Copyright © 2016年 仲琦. All rights reserved.
//

#import "ZQMeViewController.h"
#import "ZQSettingViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "ZQSquareItem.h"
#import "ZQSquareCell.h"
#import <SafariServices/SafariServices.h>
#import "ZQWebViewController.h"

static NSString * const ID = @"Square";
static CGFloat const margin = 1;
static NSInteger const cols = 4 ;
#define itemWH  (ZQScreenW - (cols - 1) *margin) / cols

@interface ZQMeViewController () <UICollectionViewDataSource ,UICollectionViewDelegate>

@property (nonatomic, strong)NSMutableArray *squareItem;

@property (nonatomic, weak)UICollectionView *collectionView;

@end


@implementation ZQMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//   self.view.backgroundColor = [UIColor orangeColor];
    [self setNavigationitem];
    
    [self loadData];
    
    [self setFootView];
    
    [self setupNote];
    
    //设置tableView组间距
    //分组样式,默认每组头部和尾部会有间距.
    self.tableView.sectionFooterHeight = ZQMargin ;
    self.tableView.sectionHeaderHeight = 0;
    
    
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
    
//    self.automaticallyAdjustsScrollViewInsets = NO;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)setupNote
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarButtonDidRepeatClick) name:ZQTabBarButtonDidRepeatClickNotification object:nil];
    
}

- (void)tabBarButtonDidRepeatClick
{
    
    if (self.tableView.window == nil) return;
    
    NSLog(@"刷新了我的界面");
    
    [self loadData];
    
}

//补格子
- (void)resolveData
{
    NSInteger count = self.squareItem.count ;
    
    NSInteger esl = count % cols ;
    
    if (esl) {
        esl = cols - esl;
        for (int a = 0; a < esl ; a++ ) {
            ZQSquareItem *item = [[ZQSquareItem alloc]init];
            [self.squareItem addObject:item];
        }
    }
    
    
}
- (void)loadData
{
    //创建请求管理者
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //创建请求数据
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"square";
    parameters[@"c"] = @"topic";

    //发送请求
    
    [manager GET:ZQRequestURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSArray *dictArr = responseObject[@"square_list"];
        
        // 字典数组转换层模型数组
        _squareItem = [ZQSquareItem mj_objectArrayWithKeyValuesArray:dictArr];
        
        [_collectionView reloadData];
        
        [self resolveData];
        
        
        //设置collectionView高度
        NSInteger itemCount =  self.squareItem.count;
        
        NSInteger row = (itemCount - 1) / cols + 1 ;
        
        CGFloat collectionH = row * itemWH + (row - 1) * margin;
        
        _collectionView.zq_height = collectionH;
        
        self.tableView.tableFooterView = _collectionView;
        
        
        //数据加载完毕 刷新tableView从新设定尺寸
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}


- (void)setFootView
{
    //创建流水布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    

    //设置cell的尺寸
    
    layout.itemSize = CGSizeMake(itemWH, itemWH);
    layout.minimumInteritemSpacing = margin;
    layout.minimumLineSpacing = margin ;
    
    //创建collectionView
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
    
    //设置背景色
    collectionView.backgroundColor = ZQGlobeColor;
    
    //设置 tableView的footview 为 流水布局
    self.tableView.tableFooterView = collectionView;
    
    //取消掉collectionView 的 scrollsToTop 属性, 那么TableView的属性就可以正常使用了
    //-------------------------------
    collectionView.scrollsToTop = NO;
    //-------------------------------
    
    _collectionView = collectionView;
    
    //设置数据源 和 代理
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    //加载 xib中的 collectionView
    [collectionView registerNib:[UINib nibWithNibName:@"ZQSquareCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.squareItem.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    ZQSquareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    cell.item = self.squareItem[indexPath.row];
    

    
    
    return cell;
    
    
    
}


//点击 view时调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    ZQSquareItem *item = self.squareItem[indexPath.row];
    
    //判断不为http 返回
    if (![item.url containsString:@"http"]) return;
    
    NSURL *url = [NSURL URLWithString:item.url];
    
    ZQWebViewController *web = [[ZQWebViewController alloc]init];
    
    web.url = url;
    
    [self.navigationController pushViewController:web animated:YES];
    
//    SFSafariViewController *safar = [[SFSafariViewController alloc]initWithURL:url];
//    
//    [self presentViewController:safar animated:YES completion:nil];
    
    
}


- (void)setNavigationitem
{
    UIBarButtonItem *item = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-moon-icon"] selImage:[UIImage imageNamed:@"mine-moon-icon-click"] target:self action:@selector(night:)];
    UIBarButtonItem *item2 = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-setting-icon"] highImage:[UIImage imageNamed:@"mine-setting-icon-click"] target:self action:@selector(setting)];

    self.navigationItem.rightBarButtonItems = @[item2, item];
    
    self.navigationItem.title = @"我的";
    
}

- (void)setting
{
    NSLog(@"点击了设置");
    ZQSettingViewController *vc = [[ZQSettingViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)night:(UIButton *)button
{
    button.selected = !button.selected;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
